/*
 * Copyright (c) 2018-2999 湖南洛云网络科技有限公司 All rights reserved.
 *
 * https://www.gz-yami.com/
 *
 */

package com.yami.shop.seckill.api.controller;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.yami.shop.bean.event.GetLivingRoomEvent;
import com.yami.shop.bean.model.Product;
import com.yami.shop.bean.model.ShopDetail;
import com.yami.shop.bean.model.Sku;
import com.yami.shop.common.i18n.I18nMessage;
import com.yami.shop.common.util.PageParam;
import com.yami.shop.config.ShopConfig;
import com.yami.shop.seckill.api.dto.SeckillProductDto;
import com.yami.shop.seckill.comment.dto.SeckillProductSimpleDto;
import com.yami.shop.seckill.api.dto.SeckillSkuDto;
import com.yami.shop.seckill.comment.model.Seckill;
import com.yami.shop.seckill.comment.model.SeckillSku;
import com.yami.shop.seckill.comment.service.SeckillService;
import com.yami.shop.seckill.comment.service.SeckillSkuService;
import com.yami.shop.service.ProductService;
import com.yami.shop.service.ShopDetailService;
import com.yami.shop.service.SkuService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import lombok.AllArgsConstructor;
import ma.glasnost.orika.MapperFacade;
import org.springframework.context.ApplicationContext;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;


/**
 * 秒杀信息
 *
 * @author LGH
 * @date 2019-08-28 09:36:59
 */
@RestController
@AllArgsConstructor
@RequestMapping("/seckill" )
@Api(tags = "秒杀商品接口")
public class SeckillProdController {

    private final SeckillService seckillService;

    private final MapperFacade mapperFacade;

    private final ProductService productService;

    private final SeckillSkuService seckillSkuService;

    private final ApplicationContext applicationContext;

    private final SkuService skuService;

    private final ShopConfig shopConfig;

    private final ShopDetailService shopDetailService;

    @GetMapping("/prod" )
    @ApiOperation(value = "获取秒杀商品信息", notes = "根据秒杀活动id，获取当前秒杀的商品信息，状态码204表示活动已结束")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "seckillId", value = "秒杀ID", required = true, dataType = "Long"),
    })
    public ResponseEntity<SeckillProductDto> getSeckillPage(Long seckillId) {

        // 秒杀活动信息（来自缓存）
        Seckill seckill = seckillService.getSeckillById(seckillId);

        // 秒杀已经下线
        if (seckill == null || Objects.equals(seckill.getStatus(), 0)) {
            return ResponseEntity.noContent().build();
        }
        // 判断是否删除
        if(Objects.equals(seckill.getIsDelete(), 1)){
            return ResponseEntity.noContent().build();
        }
        // 秒杀结束时间
        if (seckill.getEndTime().getTime() < System.currentTimeMillis()) {
            return ResponseEntity.noContent().build();
        }
        // 商品信息（来自缓存）
        Product product = productService.getProductByProdId(seckill.getProdId(), I18nMessage.getDbLang());
        // 发送事件，获取商品可用的正在开播直播间
        applicationContext.publishEvent(new GetLivingRoomEvent(seckill.getProdId(),product));
        // 商品下线，状态异常时
//        if (product == null || Objects.equals(product.getStatus(), 0)) {
        if (product == null || !Objects.equals(product.getStatus(), 1)) {
            return ResponseEntity.noContent().build();
        }

        // 店铺详情（来自缓存）
        ShopDetail shopDetail = shopDetailService.getShopDetailByShopId(product.getShopId());

        SeckillProductDto seckillProductDto = mapperFacade.map(product, SeckillProductDto.class);
        seckillProductDto.setSeckill(seckill);
        seckillProductDto.setPrice(product.getPrice());

        seckillProductDto.setShopName(shopDetail.getShopName());
        seckillProductDto.setShopId(shopDetail.getShopId());

        // 秒杀活动sku信息（来自缓存）
        List<SeckillSku> seckillSkus = seckillSkuService.listSeckillSkuBySeckillId(seckillId);

        // 商品sku信息（来自缓存）
        List<Sku> skuList = skuService.listByProdId(product.getProdId(), I18nMessage.getDbLang());


        List<SeckillSkuDto> seckillSkuDtos = seckillSkus.stream().map(seckillSku -> {

            SeckillSkuDto seckillSkuDto = new SeckillSkuDto();
            for (Sku sku : skuList) {
                if (!Objects.equals(sku.getSkuId(), seckillSku.getSkuId())) {
                    continue;
                }
                seckillSkuDto.setProdName(sku.getProdName());
                seckillSkuDto.setPic(sku.getPic());
                seckillSkuDto.setProperties(sku.getProperties());
                seckillSkuDto.setSeckillId(seckillId);
                seckillSkuDto.setPrice(sku.getPrice());
                seckillSkuDto.setSeckillPrice(seckillSku.getSeckillPrice());
                seckillSkuDto.setSeckillStocks(seckillSku.getSeckillStocks());
                seckillSkuDto.setSkuId(sku.getSkuId());
                seckillSkuDto.setSeckillSkuId(seckillSku.getSeckillSkuId());
            }

            return seckillSkuDto;
        }).collect(Collectors.toList());

        seckillProductDto.setSkuList(seckillSkuDtos);
        return ResponseEntity.ok(seckillProductDto);
    }


    @GetMapping("/pageProd")
    @ApiOperation(value = "秒杀商品列表（分页）", notes = "分页获取秒杀商品列表")
    public ResponseEntity<IPage<SeckillProductSimpleDto>> pageProd(PageParam<SeckillProductSimpleDto> page) {
        return ResponseEntity.ok(seckillService.pageSeckillProd(page,I18nMessage.getDbLang()));
    }


    @GetMapping("/indexList")
    @ApiOperation(value = "首页中的秒杀商品列表", notes = "获取最新前5条秒杀商品数据")
    public ResponseEntity<List<SeckillProductSimpleDto>> indexList() {
        PageParam<SeckillProductSimpleDto> page = new PageParam<>();
        page.setSearchCount(false);
        page.setCurrent(1L);
        page.setSize(5);
        page.setTotal(5);
        IPage<SeckillProductSimpleDto> prodPage = seckillService.pageSeckillProd(page, I18nMessage.getDbLang());
        return ResponseEntity.ok(prodPage.getRecords());
    }

}
